﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bowling.Test
{
    public class RollRecord
    {
        public RollRecord(int[] rolls)
        {
            Frames = new List<Frame>();
            Rolls = rolls;
            RecordRolls();
        }

        public List<Frame> Frames { get; set; }
        public int[] Rolls { get; set; }



        private void RecordRolls() 
        {
            var rollStack = new Stack<int>(Rolls.Reverse());
            int frameNumber = -1;
            int totalRolls = rollStack.Count;

            while (rollStack.Count > 0) {
                frameNumber++;
                int roll1Index = totalRolls - rollStack.Count;
                int roll1 = rollStack.Pop();
                int? roll2;
                int? bonus = null;

                bonus = GetSecondRoll(rollStack, frameNumber, roll1, bonus, out roll2);

                Frame frame = new Frame() {
                    FrameNumber = frameNumber,
                    Roll1 = roll1,
                    Roll2 = roll2,
                    Bonus = bonus,
                    Roll1BallIndex = roll1Index
                };

                Frames.Add(frame);
            } // while

        }

        private int? GetSecondRoll(Stack<int> rollStack, int frameNumber, int roll1, int? bonus, out int? roll2)
        {
            roll2 = isFinalRoll(frameNumber)
                        ? GetFinalRoll(rollStack, roll1, ref bonus) 
                        : GetNonFinalRoll(rollStack, roll1);
            return bonus;
        }

        private bool isFinalRoll(int frameNumber)
        {
            return frameNumber == 9;
        }


        private int? GetNonFinalRoll(Stack<int> rollStack, int roll1)
        {
            int? roll2 = roll1 == 10 ? 
                (int?) null 
                : rollStack.Pop();
            return roll2;
        }

        private int? GetFinalRoll(Stack<int> rollStack, int roll1, ref int? bonus)
        {
            int? roll2;
            roll2 = rollStack.Pop();
            if (roll1 == 10 || (roll1 + roll2 == 10)) bonus = rollStack.Pop();
            return roll2;
        }
    }
}
